package com.zp.server.server.netty;

import com.zp.server.conf.NettyConfProperties;
import com.zp.server.server.ZpServer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;

/**
 * @author zhangpeng
 * @version 1.0.0
 * @date 2019/6/22 14:44
 * @since 1.0
 */
@Component
@Log4j2
public class NettyZpServer implements ZpServer {

    private ServerBootstrap serverBootstrap;

    private NettyConfProperties nettyProperties;


    @Autowired
    private NioEventLoopGroup bossGroup;

    @Autowired
    private NioEventLoopGroup workerGroup;

    public NettyZpServer(ServerBootstrap serverBootstrap, NettyConfProperties nettyProperties) {
        this.serverBootstrap = serverBootstrap;
        this.nettyProperties = nettyProperties;
    }


    @Override
    public void start() {
        log.info("start 启动。。。。");
        try {
            ChannelFuture channelFuture = serverBootstrap.bind(nettyProperties.getPort()).sync();
            Channel channel = channelFuture.channel();
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            log.info("[出现异常] 释放资源",e);

            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }


    @PreDestroy
    @Override
    public void stop() {
        log.info("stop 释放资源");
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
